<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Reservation extends CI_Controller {
	private  $currentyear;
function __construct()
    {
        parent::__construct();
    	$this->load->library('session');
    	$this->load->library('email');
		$this->load->helper('url');
    	$this->load->database();
    	$this->load->model("centermod");
    	$this->currentyear=date("Y");
    	$this->load->library('email');
    	
	}


	//funciton randon hash
function RandomString()
    {
   	$result = "";
	$charPool = '0123456789abcdefghijklmnopqrstuvwxyz';
	for($p = 0; $p<15; $p++)
		$result .= $charPool[mt_rand(0,strlen($charPool)-1)];
	return sha1(md5(sha1($result)));

    }
  
//################### section load page##################
/*
 * add new tour
 * 
 * */	
	function listtours()
			{
			//$this->session->unset_userdata('user');
				$code=$this->input->get_post("code");
				if($code!="")
				{
					$sessionid=$this->RandomString();
					$info=array("idtransc"=>$sessionid);
					$this->session->set_userdata($info);
					$listtours=$this->centermod->ltourbycode($code);
					$date=array("listtours"=>$listtours);
					$this->load->view("stepone",$date);
				}
								
			}//function page listtour

		function getsessionid()
			{
				print_r($this->session->userdata("idtransc"));
			}
		
			
	//etap 2 remplier le infomaiton de client
		function bookingtour()
		{
			if($this->session->userdata("idtransc")!=false)
			{
				$idtours=$this->input->get_post("idtours");
	//si session le idtour exit 
	
				//$listbusinfo=$this->centermod->lbus($idtour);
				$totaldipoplace_array=$this->centermod->dispoplace($idtours);
				$totaldipoplace=$totaldipoplace_array[0]["total"];
				if($totaldipoplace>0)
				{
					//stock le idtour in session
					$info=array("idtour"=>$idtours);
					$this->session->set_userdata($info);
					$listforfait=$this->centermod->lforfaitbyid($idtours);
					$infotour=$this->centermod->ltourbyid($idtours);
					$data=array("listforfait"=>$listforfait,"infotour"=>$infotour,"totaldipoplace"=>$totaldipoplace)	;
					$info=array("idtour"=>$idtours);
					$this->session->set_userdata($info);
					$this->load->view("steptwo",$data);
				
				}else
				{
	//todo: page cotact us pour reservation tant que pas de place maintenant	
					redirect("/reservation/notplace", "refresh");			
				}
		}else
			{
				//return to page  page bus tours			
				//echo "return to page  page bus tours";
				redirect("/reservation/erropage/error87", "refresh");
				
			}
		}
		
		
//etap3 confimation

		function confirmbooking()
		{
			if($this->session->userdata("idtransc")!=false && $this->session->userdata("idtour")!=false)
			  {
				$idtransc=$this->session->userdata("idtransc");
			  	$firstname=$this->input->get_post("firstname");
				$lastname=$this->input->get_post("lastname");
				$telphone=$this->input->get_post("telphone");
				$email=$this->input->get_post("email");
				$language=$this->input->get_post("language");
				$numberpeople=$this->input->get_post("numberpeople");
				$nbchild=$this->input->get_post("nbchild");
				
				$idtours=$this->session->userdata("idtour");
				$infotour=$this->centermod->ltourbyid($idtours);
				if($infotour[0]["forfaittype"]==0)
				{
					$forfaitarr=$this->centermod->selectforfait($idtours,0);
				}elseif ($infotour[0]["forfaittype"]==1){	
					$forfaitarr=$this->centermod->selectforfait($idtours,$numberpeople);
				}
				
				$data=array("firstname"=>$firstname,"lastname"=>$lastname,"telphone"=>$telphone,
				"language"=>$language,"email"=>$email,"numberpeople"=>$numberpeople,"nbchild"=>$nbchild);
				$this->session->set_userdata($data);
				//print_r($this->session->userdata("idtransc")."--".$this->session->userdata("idtour")."data=>".$this->session->userdata("firstname"));
				$idtrasacton=substr( $this->session->userdata("idtransc") ,0,8 );
				$data1=array("idtransc"=>$idtransc,"firstname"=>$firstname,"lastname"=>$lastname,"telphone"=>$telphone,
				"language"=>$language,"email"=>$email,"numberpeople"=>$numberpeople,"nbchild"=>$nbchild,"infotour"=>$infotour,"forfaitarr"=>$forfaitarr);
				$this->load->view("stepthree",$data1);
						
		
		}else 
		  {
		  	redirect("/reservation/erropage/error125", "refresh");
		  }
		
		}
	 function receipt()
	 {
		
	 	date_default_timezone_set('America/Montreal');
	 	
	 	if($this->input->get_post("cust_id")!=false && $this->input->get_post("response_order_id")!=false)
	 	{
			
	 		$idtransc=$this->input->get_post("cust_id");
	 		$arr_idtransc=$arrtransaction=$this->centermod->cketranction($idtransc);
	 		if(count($arr_idtransc)==1){
	 			if($arr_idtransc[0]["response_order_id"]==null)
	 			{

			 		$idtours=$arr_idtransc[0]["idtour"];
			 		$firstname=$this->input->get_post("bill_first_name");
					$lastname=$this->input->get_post("bill_last_name");
					$telphone=$this->input->get_post("bill_phone");
					$email=$this->input->get_post("email");
					$language=$arr_idtransc[0]["language"];
					$numberpeople=$arr_idtransc[0]["numberpeople"];
					$nbchild=$arr_idtransc[0]["nbchild"];
					$salesprice=str_replace(',','',$this->input->get_post("charge_total"));
					$response_order_id=$this->input->get_post("response_order_id");
					$response_code=$this->input->get_post("response_code");
					$date_stamp=$this->input->get_post("date_stamp");
					$time_stamp=$this->input->get_post("time_stamp");
					//function model
			 		//seachclientbytel
			 		//$listbusinfo=$this->centermod->lbus($idtour)
			 		//$this->session->userdata("idtour")
			 	
			 	
			 	//	$firstname="xiaoming1";
					//$lastname="wang";
				//	$telphone="514-4474158";
				if($response_code<50)
				{
					
			 		$webnom="";
			 		$isexitclient=$this->centermod->seachclientbytel("$telphone");
	 			if(count($isexitclient)>0)
	 				{
	 			//exit
	 				if($isexitclient[0]["firstname"]==$firstname &&$isexitclient[0]["lastname"]==$lastname)
	 				{
	 					//meme nom et prenom
	 				$idclient=$isexitclient[0]["idclients"];
	 				
	 				
	 				}else
	 				{
	 				
	 				//diff nom et prenom efecture new name to webnom
	 				$webnom=$firstname."|".$lastname."|".$email;
	 				$idclient=$isexitclient[0]["idclients"];
	 				//print_r($idclient);
	 				/*
	 				$date_webnom=array("webnom"=>$webnom);
	 				$where_webnom="idclients=$idclient";
	 				$this->centermod->updatetemplate("clients",$date_webnom,$where_webnom);
	 				*/
	 				}
	 			
				
	 		}else 
	 		{
	 			// no exit le client 
	 			$data_newclient=array("firstname"=>$firstname,"lastname"=>$lastname,"telphone"=>$telphone,"email"=>$email,"language"=>$language);
	 			$idclient=$this->centermod->insertetemplate("clients",$data_newclient);
	 		}
 			
	 	
	 	//reservation le place dans bus
			$totalplacereserved=$numberpeople+$nbchild;
			 $listbus=$this->centermod->lbus($idtours);
			 $idbus="";
			 foreach ($listbus as $ls)
			 {
			 	if($ls["seatavaible"]>=$totalplacereserved)
			 	{
			 		$afterreservedplace=$ls["seatavaible"]-$totalplacereserved;
			 		$idbus=	$ls["idbus"];
			 		break;
			 		
			 		
			 	}
			 	
			 }
		
			 	$idarr_bookingsalse=$this->centermod->getbookingsalse();

			 	if($idbus!="")
	 			{

	 				if(count($idarr_bookingsalse)==1){
	 				$date_bus_reservation=array("seatavaible"=>$afterreservedplace);
	 				$where_bus_reservation=array("idbus=$idbus");
	 				$this->centermod->updatetemplate("bus",$date_bus_reservation,$where_bus_reservation);
	 				//inscription
	 				if($webnom!="")
	 				{
	 						$date_inscr=array("salesprice"=>$salesprice,"numberpeople"=>$numberpeople,"nbchild"=>$nbchild,"chambre"=>$numberpeople,
	 						"reminder"=>"webreserved","orginalprice"=>$salesprice,"chambreqty"=>1,"paid"=>1,"fk_idbus"=>$idbus,"fk_idclients"=>$idclient,"nameonline"=>$webnom);
	 				}else 
	 				{
	 						$date_inscr=array("salesprice"=>$salesprice,"numberpeople"=>$numberpeople,"nbchild"=>$nbchild,"chambre"=>$numberpeople,"reminder"=>"webreserved","orginalprice"=>$salesprice,"chambreqty"=>1,"paid"=>1,"fk_idbus"=>$idbus,"fk_idclients"=>$idclient);
	 				}
	 				
	 				$idinscr=$this->centermod-> insertetemplate("inscriptions",$date_inscr);
      				$data_invoice=array("typepaiement"=>"credit","createdtime"=>date('Y-m-d H:i:s'));
      				$idinvoice=$this->centermod-> insertetemplate("invoice",$data_invoice);
      				$idarr_bookingsalse=$this->centermod-> getbookingsalse();
      				$users_idusers=$idarr_bookingsalse[0]["idusers"];
	 				 $datainvoicerelatif=array("insrc_idinscriptions"=>$idinscr,"inv_idinvoice"=>$idinvoice,"users_idusers"=>$users_idusers);
      				$idinsert_relatif=$this->centermod-> insertetemplate("relatif_invoice",$datainvoicerelatif);
      //add to table transcation
					$data_transcationtable=array("bill_first_name"=>$firstname,"bill_last_name"=>$lastname,"bill_phone"=>$telphone,"response_order_id"=>$response_order_id,"response_code"=>$response_code,"date_stamp"=>$date_stamp,"time_stamp"=>$time_stamp,"idvoice"=>$idinvoice);
      				$idtr=$this->centermod->updatetemplate("transcation",$data_transcationtable,"idtransc='$idtransc'");
     				$linfoper=$this->centermod->seachclientbyid($idclient);
      				$infoallforinvoice=$this->centermod->allinfoforinvoice($idinscr);
      				 $data_invoice["infoper"]=$linfoper;
     				 $data_invoice["allinfo"]=$infoallforinvoice;
      				 $data_invoice["idinvoice"]=$idinvoice;
     				 $message=$this->load->view("invoices",$data_invoice,true);
					 $config=array( 'mailtype' => 'html');
					 $this->email->initialize($config);
					  $this->email->from('wangxiaoming@themjwebsolutions.com', 'tourfantaisie Inc');
					$this->email->to($email); 
					$this->email->subject('Invoice/Facture Online Booking');
					$this->email->message($message);	
					$this->email->send();
	 				//echo $this->email->print_debugger();
	 				redirect('/reservation/endingpage', 'refresh');
	 			
	 				}else 
	 				{
	 					//echo "not found your onlinebooking sales ";
	 					$data_transcationtable=array("bill_first_name"=>$firstname,"bill_last_name"=>$lastname,"bill_phone"=>$telphone,"response_order_id"=>$response_order_id,"response_code"=>$response_code,"date_stamp"=>$date_stamp,"time_stamp"=>$time_stamp,"erreurtracking"=>"onlinebooking sales note exit 273");
      					$idtr=$this->centermod->updatetemplate("transcation",$data_transcationtable,"idtransc='$idtransc'");
	 					redirect("/reservation/erropage/error265", "refresh");
	 					
	 				}
	 				
	 				

	 			
	 			}else
	 			{
	 				//email bus complete
	 				//echo "not enough place";
	 					$data_transcationtable=array("bill_first_name"=>$firstname,"bill_last_name"=>$lastname,"bill_phone"=>$telphone,"response_order_id"=>$response_order_id,"response_code"=>$response_code,"date_stamp"=>$date_stamp,"time_stamp"=>$time_stamp,"erreurtracking"=>"place not enough 285");
      					$idtr=$this->centermod->updatetemplate("transcation",$data_transcationtable,"idtransc='$idtransc'");
	 				redirect("/reservation/notplace", "refresh");
	 			}
				}else //trascation not prever id 
					{
						$data_transcationtable=array("bill_first_name"=>$firstname,"bill_last_name"=>$lastname,"bill_phone"=>$telphone,"response_order_id"=>$response_order_id,"response_code"=>$response_code,"date_stamp"=>$date_stamp,"time_stamp"=>$time_stamp,"erreurtracking"=>"transcation not preved");
      					$idtr=$this->centermod->updatetemplate("transcation",$data_transcationtable,"idtransc='$idtransc'");
						redirect("/reservation/erropage/error287", "refresh");
					}
	 				
	 			}else  //else  idtranc est null
	 			{
	 			
	 				//todo: goto page bustour	
	 				redirect("/reservation/erropage/error300", "refresh");
	 				
	 				
	 			}
	 		}else // db colunne response_order_id deja exit 
	 		{
	 	//todo: goto page bustour	
	 			redirect("/reservation/erropage/error306", "refresh");
	 		
	 		}	
	 
	 	
	 	}else 
	 	{
	 		//echo not finish transcation moneris not found idtranscation
	 	    redirect("/reservation/erropage/error296", "refresh");
	 	
	 	}
	 
	 	
	 } 	
	 

function endingpage()
{
	$this->load->view("stepending");
}

//stock info tranctajax

	function writeinoftranc()
	{
		if($this->session->userdata("idtransc")!=false &&$this->session->userdata("firstname")!=false&&$this->session->userdata("lastname")!=false
		&&$this->session->userdata("telphone")!=false&&$this->session->userdata("email")!=false&&$this->session->userdata("numberpeople")!=false
		&&$this->session->userdata("idtour")!=false)
		
		{
			$arrtransaction=$this->centermod->cketranction($this->session->userdata("idtransc"));
			$data=array("idtransc"=>$this->session->userdata("idtransc"),
					"idtour"=>$this->session->userdata("idtour"),
					"bill_first_name"=>$this->session->userdata("firstname"),
					"bill_last_name"=>$this->session->userdata("lastname"),
					"bill_phone"=>$this->session->userdata("telphone"),
					"language"=>$this->session->userdata("language"),
					"email"=>$this->session->userdata("email"),
					"numberpeople"=>$this->session->userdata("numberpeople"),
					"nbchild"=>$this->session->userdata("nbchild"));
			if(count($arrtransaction)==0)
			{
				$idtransaction=$this->centermod-> insertetemplate("transcation",$data);
				echo "yes";
			}
			else if(count($arrtransaction)==1)
			{
				$idtransc=$this->session->userdata("idtransc");
				$this->centermod->updatetemplate("transcation",$data,"idtransc='$idtransc'");
				echo "yes";
			}else 
			{
				echo "no";
			}
			
		}else 
		{
			echo $this->session->userdata("idtransc")."---".$this->session->userdata("firstname")."---".$this->session->userdata("lastname")."---".
		$this->session->userdata("telphone")."---".$this->session->userdata("language")."---".
		$this->session->userdata("email")."---".$this->session->userdata("numberpeople")."---".$this->session->userdata("nbchild")."---".$this->session->userdata("idtour");
		}
	}
	

// return page function
function erropage($id)
{
	$this->load->view("returnbustour");
}	

function notplace()
{
	$this->load->view("returnbustour");
}

function pages($pagename)
{
	$this->load->view($pagename);
}


	
/* end reservation online booking*/	
/*###########################################################################################################################*/
		
	/*list le chambre information by idtour*/
			function getlcountchambre($idtour)
			{
				$listbusinfo=$this->centermod->lbus($idtour);
				foreach ($listbusinfo as $lbus)
				{
					$idbus=$lbus["idbus"];
					$ldetailchambre=$this->centermod->countchambre($idbus);
					for($i=1;$i<=4;$i++)
					{
						$lchambre["$i"]=0;
						foreach ($ldetailchambre as $lc)
						{
							if($i==$lc["chambre"])
							{
								$lchambre["$i"]=$lc["total"];
								
							}
						}
						
					}
					$lchambrebybus["$idbus"]=$lchambre;
				}
				
				echo json_encode($lchambrebybus); 
			
			}	
			
			

		
			
			
			
			
			
/* get place info*/
			function getplaceinfo($idtours)
			{
				 $listbus=$this->centermod->lbus($idtours);
				 foreach($listbus as $lb)
				 {
				$this->centermod->sustactionper($lb["idbus"]);
				 }	
				$placeinfo=$this->centermod->getplaceinfo($idtours);
							
				foreach ($placeinfo as $pi)
				{
					$returnarr[$pi["idbus"]]["seatqty"]=$pi["seatqty"];
					$returnarr[$pi["idbus"]]["seatavaible"]=$pi["seatavaible"];
				}
				
				echo json_encode($returnarr); 
			}			
	
/*list detail*/			
		function listdetail($idbus,$idtour)
			{
			//$this->session->unset_userdata('user');
		if($this->session->userdata("user")==false)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else 
			{
				$level=$this->session->userdata("level");
				$linfobus=$this->centermod->linfodetail($idbus,$idtour);
				$lclientinbus=$this->centermod->lclientdetail($idbus,$idtour);
				$lgroup_person_infor=$this->centermod->getclientgourpid($idbus,$idtour);
				$listgroup=array();
				foreach ($lgroup_person_infor as $lpi)
				{
					
					$lgroupelement["person"]=$lpi;
					$lgroup_chmabre_infor=$this->centermod->lclientdetailbygourp($idbus,$idtour,$lpi["fk_idclients"]);
					$lgroupelement["chambre"]=$lgroup_chmabre_infor;
					$listgroup[]=$lgroupelement;
					}
				$date=array("linfobus"=>$linfobus,"lclientinbus"=>$lclientinbus,"lgroup"=>$listgroup,"idbus"=>$idbus,"idtour"=>$idtour,"level"=>$level);
				$this->load->view("listdetail",$date);
				
			}//no login
			}//function page listtour		

			
//ckplacevalid
function ckplacevalid($idbus)
{
	$placevalid=$this->centermod->getvalidplace($idbus);
		
				echo json_encode($placevalid[0]["seatavaible"]);
}

function viewinvoice()
	{
				//$this->session->unset_userdata('user');
		if($this->session->userdata("user")==false)
			{
					header('Location:index.php?pages/loginadmin');
						
			}else 
			{
		$idinvoice=$this->input->get_post("idinvoice");
		$idclient=$this->input->get_post("idclient");
		$idinscriptions=$this->input->get_post("idinscriptions");;
		$linfoper=$this->centermod->seachclientbyid($idclient);
      	$infoallforinvoice=$this->centermod->allinfoforinvoice($idinscriptions);
      	 $data_invoice["infoper"]=$linfoper;
      	$data_invoice["allinfo"]=$infoallforinvoice;
     	 $data_invoice["idinvoice"]=$idinvoice;
     	 $data_invoice["from"]="listdetail";
    	 $this->load->view("invoices",$data_invoice);
			}
	}
	
	
function viewinvoicegrp()
	{
		$idinvoice=$this->input->get_post("idinvoice");
		$idclient=$this->input->get_post("idclient");
		$idinscriptions=$this->input->get_post("idinscriptions");
		$id_inscr_arr=explode(",", $idinscriptions);
		
				foreach($id_inscr_arr as $idinscr)
					{
      					$infoallforinvoice[]=$this->centermod->allinfoforinvoice($idinscr);
      				}
      	$linfoper=$this->centermod->seachclientbyid($idclient);			  		
		
		
		
		$linfoper=$this->centermod->seachclientbyid($idclient);
      	$data_invoice["idinvoice"]=$idinvoice;	
	 	$data_invoice["infoper"]=$linfoper;
     	$data_invoice["allinfo"]=$infoallforinvoice;
     	 $data_invoice["idinvoice"]=$idinvoice;
     	 $data_invoice["from"]="listdetail";
     	$this->load->view("invoicesgroup",$data_invoice);
     	
	}	
	
// liste user
function  listuser()
	{
				//$this->session->unset_userdata('user');
		if($this->session->userdata("user")==false ||$this->session->userdata("level")!="admin")
			{
					header('Location:index.php?pages/loginadmin');
						
			}else 
			{
				$listusers=$this->centermod->getusers();
				$data=array("listusers"=>$listusers);
				$this->load->view("listuser",$data);
				
				
			}
	}
	

	
			
}//class
